package com.example.nkj.feather_android;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;

import java.text.SimpleDateFormat;
import java.util.Date;

//import android.bluetooth.le.ScanCallback;
//import android.bluetooth.le.ScanResult;
//import android.os.AsyncTask;

/**
 * Created by nkj on 18-11-4.
 */

public class htu_ble_scan_adv extends AppCompatActivity {

    private BluetoothAdapter bluetoothAdapter;
    BluetoothManager bluetoothManager;
    BluetoothLeScanner bluetoothScanner;
    private BluetoothAdapter.LeScanCallback mLeScanCallback;

    private ToggleButton togglebutton_scan;
    private TextView ble_title;
    private TextView ble_result;
    private int scan_count = 0;
    private EditText filter_data;

    private TextView rv;
    private TextView rvol;
    private TextView rad;
    private TextView batv;
    private TextView bat_vol;
    private TextView bat_ad;
    private TextView sv;
    private EditText rk;

    private static final String[] scanning = new String[]{
        ".", "..","..."
    };

    private final static int REQUEST_ENABLE_BT = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //设置标题栏
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle(R.string.htu_title_name);
        }
        setContentView(R.layout.htu_ble_scan_adv);


        filter_data = (EditText)findViewById(R.id.filter_editText);
        ble_title = (TextView) this.findViewById(R.id.textView_ble_scan);
        ble_title.setText("HTU Scaning\r\n");
        ble_result = (TextView) this.findViewById(R.id.textView_ble_scan_result);
        ble_result.setMovementMethod(ScrollingMovementMethod.getInstance());
        ble_result.setText("HTU Scan\r\n");

        togglebutton_scan = (ToggleButton) findViewById(R.id.toggleButton_ble_scan);
        togglebutton_scan.setOnCheckedChangeListener(toggleButtonOnCheckedChangeListener);

        rv = (TextView) this.findViewById(R.id.textView_rv);
        rvol = (TextView) this.findViewById(R.id.textView_rvol);
        rad = (TextView) this.findViewById(R.id.textView_rad);
        batv = (TextView) this.findViewById(R.id.textView_batv);
        bat_vol = (TextView) this.findViewById(R.id.textView_bat_vol);
        bat_ad = (TextView) this.findViewById(R.id.textView_bat_ad);
        sv = (TextView) this.findViewById(R.id.textView_sv);
        rk = (EditText)findViewById(R.id.editText_rkv);

        //判断手机是否支持BLE
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            ble_result.setText("not support BLE");
            startActivity(new Intent(htu_ble_scan_adv.this,MainActivity.class));
            finish();
        }

        //mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        bluetoothScanner = bluetoothAdapter.getBluetoothLeScanner();

        if(bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                // 解析广播数据
                parseScanAdvData(device,rssi,scanRecord);
            }
        };

    }

    private void add_text_to_view(TextView view, CharSequence text) {
        view.append(text);
        final int scrollAmount = view.getLineCount() * view.getLineHeight();
        if (scrollAmount > view.getHeight()) {
            view.scrollTo(0, scrollAmount - view.getHeight());
        }
    }

    private ToggleButton.OnCheckedChangeListener toggleButtonOnCheckedChangeListener = new ToggleButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()) {
                case R.id.toggleButton_ble_scan:
                    if (isChecked) {
                        // 开始扫描设备
                        ble_title.setText("HTU Scaning");
                        bluetoothAdapter.startLeScan(mLeScanCallback);
                        //startScanning();
                    } else {
                        // 停止扫描设备
                        ble_title.setText("HTU Stoped");
                        bluetoothAdapter.stopLeScan(mLeScanCallback);
                        //stopScanning();
                    }
                    break;
            }
        }
    };

    // Device scan callback.
//    private ScanCallback leScanCallback = new ScanCallback() {
//        @Override
//        public void onScanResult(int callbackType, ScanResult result) {
//            add_text_to_view(ble_result,"Device Name: " + result.getDevice().getName() + " rssi: " + result.getRssi() + "\r\n");
//        }
//    };
//
//    public void startScanning() {
//        System.out.println("start scan\r\n");
//        add_text_to_view(ble_result, "start scan\r\n");
//        AsyncTask.execute(new Runnable() {
//            @Override
//            public void run() {
//                bluetoothScanner.startScan(leScanCallback);
//            }
//        });
//    }
//
//    public void stopScanning() {
//        System.out.println("stopping scan\r\n");
//        add_text_to_view(ble_result, "stop scan\r\n");
//        AsyncTask.execute(new Runnable() {
//            @Override
//            public void run() {
//                bluetoothScanner.stopScan(leScanCallback);
//            }
//        });
//    }

    private void parseScanAdvData(BluetoothDevice device,int rssi,byte[] scanRecord) {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");//设置日期格式
        String fd = filter_data.getText().toString().toUpperCase();
        String scandata = new String(scanRecord).toUpperCase();

        boolean is_str_str = scandata.contains(fd) || byteToHex(scanRecord).contains(fd) || device.getAddress().toUpperCase().contains(fd);

        if(is_str_str || fd.length()==0) {
            scan_count ++;
            add_text_to_view(ble_result, "scan..." + scan_count + "\r\n");
            add_text_to_view(ble_result, "time: " + df.format(new Date()) + "\r\n");
            add_text_to_view(ble_result, "name: " + device.getName() + "\r\n");
            add_text_to_view(ble_result, "addr: " + device.getAddress() + "\r\n");
            add_text_to_view(ble_result, "rssi: " + rssi + "dB\r\n");
            add_text_to_view(ble_result, "data: " + byteToHex(scanRecord) + "\r\n\r\n");

            float k = Float.parseFloat(rk.getText().toString())/1000000;
            int sd[] = bytesToInt(scanRecord);
            if(sd[16] == 0xFF && sd[17] == 0xFF){
                rv.setText("NC");
            }
            else {
                float frv = (sd[16]*256+sd[17])*k+0.00005f;//Float.toString(frv)
                rv.setText(String.format("%.4f",frv)+"MΩ");
            }
            rvol.setText(String.valueOf((sd[18]*256+sd[19]))+"mv");
            rad.setText(String.valueOf((sd[20]*256+sd[21])));
            batv.setText(String.valueOf((sd[22]))+"%");
            bat_vol.setText(String.valueOf((sd[23]*256+sd[24]))+"mv");
            bat_ad.setText(String.valueOf((sd[25]*256+sd[26])));
            byte d[] = {scanRecord[27]};
            sv.setText("0x"+byteToHex(d));

            ble_title.setText("HTU Scaning" + scanning[scan_count % 3]);
        }
    }

    public void onScanButtonClick(View view)
    {
        switch(view.getId())
        {
            case R.id.button_ble_scan_back:
                togglebutton_scan.setChecked(false);
                bluetoothAdapter.stopLeScan(mLeScanCallback);
                //stopScanning();
                startActivity(new Intent(htu_ble_scan_adv.this,MainActivity.class));
                finish();
                break;
            case R.id.buttonble_scan_clear:
                ble_result.setText("");
                break;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        switch (keyCode)
        {
            case KeyEvent.KEYCODE_MENU:

                break;
            case KeyEvent.KEYCODE_BACK:
                togglebutton_scan.setChecked(false);
                bluetoothAdapter.stopLeScan(mLeScanCallback);
                //stopScanning();
                startActivity(new Intent(htu_ble_scan_adv.this,MainActivity.class));
                finish();
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 将byte数组转换为16进制字符串
     */
    public static String byteToHex(byte[] bytes)
    {
        String strHex = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < bytes.length; n++) {
            strHex = Integer.toHexString(bytes[n] & 0xFF);
            sb.append((strHex.length() == 1) ? "0" + strHex : strHex); // 每个字节由两个字符表示，位数不够，高位补0
        }
        return sb.toString().trim().toUpperCase();
    }

    /**
     * 将byte数组转换为整数数组
     */
    public static int[] bytesToInt(byte[] bytes) {
        int a[] = new int[bytes.length];
        for (int i = bytes.length - 1; i >= 0; i--) {
            a[i] = bytes[i] & 0xFF;
        }
        return a;
    }

}
